package com.hdu.h_health.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.hdu.h_health.Adapter.ChatAdapter;
import com.hdu.h_health.R;
import com.hdu.h_health.bean.User;
import com.hdu.h_health.common.BaseActivity;
import com.hdu.h_health.dependence.xlistview.XListView;
import com.hdu.h_health.model.UserModel;
import com.hdu.h_health.widget.NavigationView;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMTextMessage;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.newim.listener.MessagesQueryListener;
import cn.bmob.newim.listener.ObseverListener;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.exception.BmobException;

/**
 * 咨询会话界面
 * Created by 612 on 2016/3/8.
 */
public class ChatActivity extends BaseActivity implements View.OnClickListener, XListView.IXListViewListener, ObseverListener {

    private XListView xListView;//聊天列表
    private EditText edit_msg;//文本输入框
    private Button btn_chat_add;//添加更多
    //    private Button btn_chat_emo;//添加表情
    private Button btn_speak;//按住说话
    private Button btn_chat_voice;//录制音频
    private Button btn_chat_keyboard;//小键盘
    private Button btn_chat_send;//发送
    //表情布局
    private LinearLayout layout_more;
    private LinearLayout layout_emo;
    //添加图片，地理位置等
    private LinearLayout layout_add;
    //整个聊天界面
    private LinearLayout llChat;

    //适配器
    private ChatAdapter chatAdapter;
    //Bmob会话
    private BmobIMConversation c;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        //连接Bmob IM服务器
        User user = UserModel.getInstance().getCurrentUser();
        BmobIM.connect(user.getObjectId(), new ConnectListener() {
            @Override
            public void done(String uid, BmobException e) {
                if (e == null) {
                    Logger.i("connect success");
                } else {
                    Logger.e(e.getErrorCode() + "/" + e.getMessage());
                }
            }
        });

        //在聊天页面的onCreate方法中，通过如下方法创建新的会话实例
        BmobIMConversation conversation = (BmobIMConversation) getBundle().getSerializable("c");
        if (conversation != null) {
            c = BmobIMConversation.obtain(BmobIMClient.getInstance(), conversation);
        }

        chatAdapter = new ChatAdapter(this, c);
        xListView.setAdapter(chatAdapter);
        //取消上拉加载
        xListView.setPullLoadEnable(false);
        initChatLayout();
        initBottomView();
    }

    @Override
    protected void initView() {
        super.initView();
        xListView = (XListView) findViewById(R.id.xlistview);
        edit_msg = (EditText) findViewById(R.id.edit_msg);
        btn_chat_add = (Button) findViewById(R.id.btn_chat_add);
        btn_speak = (Button) findViewById(R.id.btn_speak);
        btn_chat_voice = (Button) findViewById(R.id.btn_chat_voice);
        btn_chat_keyboard = (Button) findViewById(R.id.btn_chat_keyboard);
        btn_chat_send = (Button) findViewById(R.id.btn_chat_send);
        layout_more = (LinearLayout) findViewById(R.id.layout_more);
        layout_add = (LinearLayout) findViewById(R.id.layout_add);
        layout_emo = (LinearLayout) findViewById(R.id.layout_emo);
        llChat = (LinearLayout) findViewById(R.id.ll_chat);

        xListView.setXListViewListener(this);
//        xListView.setOnItemClickListener();//设置列表项点击事件
        edit_msg.setOnClickListener(this);
        btn_chat_add.setOnClickListener(this);
//        btn_chat_emo.setOnClickListener(this);
        btn_chat_voice.setOnClickListener(this);
        btn_speak.setOnClickListener(this);
        btn_chat_keyboard.setOnClickListener(this);
        btn_chat_send.setOnClickListener(this);
        layout_more.setOnClickListener(this);
        layout_add.setOnClickListener(this);
        layout_emo.setOnClickListener(this);
    }



    //初始化整个布局
    private void initChatLayout() {
        llChat.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                llChat.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                //自动刷新
//                onRefresh();
//                //加载消息数据
                queryMessages(null);
            }
        });
        //设置导航栏
        navigationView = (NavigationView) findViewById(R.id.navView);
        navigationView.setTv_title(c.getConversationTitle());
        navigationView.getIv_left().setImageResource(R.drawable.ic_keyboard_arrow_left_white_36dp);
//        navigationView.getIv_right().setImageResource(R.drawable.ic_control_point_white_36dp);
        navigationView.setClickListener(new NavigationView.ClickCallBack() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
//                startActivity(new Intent(getBaseContext(), EditSecretActivity.class));
            }
        });
    }

    /**
     * 初始化底部布局
     */
    private void initBottomView() {
        /*设置输入框的触摸事件*/
        edit_msg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP) {
                    scrollToBottom();
                }
                return false;
            }
        });
        //设置输入框的文字改变事件
        edit_msg.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                scrollToBottom();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //输入框文字不为空时
                if (!TextUtils.isEmpty(s)) {
                    btn_chat_send.setVisibility(View.VISIBLE);
                    btn_chat_add.setVisibility(View.GONE);
                } else {//为空
                    btn_chat_add.setVisibility(View.VISIBLE);
                    btn_chat_send.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 各按钮点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_msg:
                onEditClick();
                break;
            case R.id.btn_chat_add:
                onAddClick();
                break;
            case R.id.btn_chat_emo:
                onEmoClick();
                break;
            case R.id.btn_chat_voice:
                onVoiceClick();
                break;
            case R.id.btn_speak:
                break;
            case R.id.btn_chat_keyboard:
                onKeyClick();
                break;
            case R.id.btn_chat_send:
                sendMessage();
                break;
        }
    }

    /**
     * 点击输入框
     */
    public void onEditClick() {
        if (layout_more.getVisibility() == View.VISIBLE) {
            layout_add.setVisibility(View.GONE);
            layout_emo.setVisibility(View.GONE);
            layout_more.setVisibility(View.GONE);
        }
    }

    /**
     * 点击加号
     */
    public void onAddClick() {
        if (layout_more.getVisibility() == View.GONE) {
            layout_more.setVisibility(View.VISIBLE);
            layout_add.setVisibility(View.VISIBLE);
            layout_emo.setVisibility(View.GONE);
            hideSoftInputView();
        } else {
            if (layout_emo.getVisibility() == View.VISIBLE) {
                layout_emo.setVisibility(View.GONE);
                layout_add.setVisibility(View.VISIBLE);
            } else {
                layout_more.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 点击表情按钮
     */
    private void onEmoClick() {
        if (layout_more.getVisibility() == View.GONE) {
            showEditState(true);
        } else {
            if (layout_add.getVisibility() == View.VISIBLE) {
                layout_add.setVisibility(View.GONE);
                layout_emo.setVisibility(View.VISIBLE);
            } else {
                layout_more.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 点击录音按钮
     */
    public void onVoiceClick() {
        edit_msg.setVisibility(View.GONE);
        layout_more.setVisibility(View.GONE);
        btn_chat_voice.setVisibility(View.GONE);
        btn_chat_keyboard.setVisibility(View.VISIBLE);
        btn_speak.setVisibility(View.VISIBLE);
        hideSoftInputView();
    }

    /**
     * 点击小键盘按钮
     */
    public void onKeyClick() {
        edit_msg.setVisibility(View.VISIBLE);
        layout_more.setVisibility(View.VISIBLE);
        btn_chat_voice.setVisibility(View.VISIBLE);
        btn_chat_keyboard.setVisibility(View.GONE);
        btn_speak.setVisibility(View.GONE);
        showSoftInputView();
    }

    /**
     * 根据是否点击笑脸来显示文本输入框的状态
     *
     * @param isEmo 用于区分文字和表情
     */
    private void showEditState(boolean isEmo) {
        edit_msg.setVisibility(View.VISIBLE);
        edit_msg.requestFocus();
        if (isEmo) {
            layout_more.setVisibility(View.VISIBLE);
            layout_more.setVisibility(View.VISIBLE);
            layout_emo.setVisibility(View.VISIBLE);
            layout_add.setVisibility(View.GONE);
            hideSoftInputView();//此方法在BaseActivity
        } else {
            layout_more.setVisibility(View.GONE);
            showSoftInputView();
        }
    }

    /**
     * 显示软键盘
     */
    public void showSoftInputView() {
        if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .showSoftInput(edit_msg, 0);
        }
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        BmobIMMessage msg = chatAdapter.getFirstMessage();
        queryMessages(msg);
        stopLoading();
    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadMore() {
        stopLoading();
    }

    /**
     * 停止刷新或加载
     */
    private void stopLoading() {
        xListView.stopRefresh();//停止下拉刷新
        xListView.stopLoadMore();//停止上拉加载
        xListView.setRefreshTime(R.string.xlistview_time);//设置刷新时间
    }

    /**
     * 发送文本消息
     */
    private void sendMessage() {
        String text = edit_msg.getText().toString();
        if (TextUtils.isEmpty(text.trim())) {
            toast("请输入内容");
            return;
        }
        BmobIMTextMessage msg = new BmobIMTextMessage();
        msg.setContent(text);
        //可设置额外信息
        Map<String, Object> map = new HashMap<>();
        map.put("level", "1");//随意增加信息
        msg.setExtraMap(map);
        c.sendMessage(msg, listener);
    }

    /**
     * 列表滚动到底部
     */
    private void scrollToBottom() {
        xListView.setSelection(xListView.getBottom());
    }

    /**
     * 消息发送监听器
     */
    public MessageSendListener listener = new MessageSendListener() {

        @Override
        public void onProgress(int value) {
            super.onProgress(value);
            //文件类型的消息才有进度值
            Logger.i("onProgress：" + value);
        }

        @Override
        public void onStart(BmobIMMessage msg) {
            super.onStart(msg);
            scrollToBottom();
            chatAdapter.addMessage(msg);
            chatAdapter.notifyDataSetChanged();
        }

        @Override
        public void done(BmobIMMessage msg, BmobException e) {
            scrollToBottom();
            chatAdapter.notifyDataSetChanged();
            edit_msg.setText("");
            if (e != null) {
                toast(e.getMessage());
            }
        }
    };

    /**
     * 首次加载，可设置msg为null，下拉刷新的时候，默认取消息表的第一个msg作为刷新的起始时间点，默认按照消息时间的降序排列
     */
    public void queryMessages(BmobIMMessage msg) {
        c.queryMessages(msg, 10, new MessagesQueryListener() {
            @Override
            public void done(List<BmobIMMessage> list, BmobException e) {
                if (e == null) {
                    if (null != list && list.size() > 0) {
                        chatAdapter.addMessages(list);
                        chatAdapter.notifyDataSetChanged();
                        scrollToBottom();
                    }
                } else {
                    toast(e.getMessage() + "(" + e.getErrorCode() + ")");
                }
            }
        });
    }

    /**
     * 接收到聊天消息
     */
    public void onEventMainThread(MessageEvent event) {
        BmobIMMessage msg = event.getMessage();
        Logger.i("接收到消息：" + msg.getContent());
//        if (c != null && event != null && c.getConversationId().equals(event.getConversation().getConversationId())) {//如果是当前会话的消息
        if (c != null && c.getConversationId().equals(event.getConversation().getConversationId())) {//如果是当前会话的消息
            chatAdapter.addMessage(msg);
            chatAdapter.notifyDataSetChanged();
            //更新该会话下面的已读状态
            c.updateReceiveStatus(msg);
            scrollToBottom();
        } else {
            Logger.i("不是与当前聊天对象的消息");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        //需要在onResume中注册EventBus
//        EventBus.getDefault().activity_register(this);
        //添加通知监听
        BmobNotificationManager.getInstance().addObserver(this);
        // 有可能锁屏期间，在聊天界面出现通知栏，这时候需要清除通知
        BmobNotificationManager.getInstance().cancelNotification();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        //需要在onPause中取消注册EventBus
//        EventBus.getDefault().unregister(this);
        //取消通知栏监听
        BmobNotificationManager.getInstance().removeObserver(this);
    }

    @Override
    protected void onDestroy() {
        //更新此会话的所有消息为已读状态
        hideSoftInputView();
        c.updateLocalCache();
        super.onDestroy();
    }
}
